<?php



namespace App\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

/**
 * 用户推荐
 */
class UserRecommand extends Model
{
    protected $table = 'user_recommand';

    protected $fillable = [
        'user_id', 'rec_user_ids', 'flag'
    ];

    const STATUS_UNREAD = 0;
    const STATUS_READ = 1;

    /**
     * 初始化用户推荐
     */
    static function init($userId = 0, $gender = 0)
    {
        //已经推荐过的
        $where = ['user_id' => $userId];
        $item = self::where($where)->orderBy('id', 'desc')->first();
        $recUserIds = $item && $item->rec_user_ids ? json_decode($item->rec_user_ids, true) : [];

        //未读
        if ($item && $item->flag == self::STATUS_UNREAD) return $recUserIds;

        //筛选推荐
        $where = ['role' => UserProfile::ROLE_HOST];
        $recUserIds[] = $userId;
        $recUers = UserProfile::where($where)->whereNotIn('user_id', $recUserIds)->orderBy(Db::raw('rand()'))->limit(10)->pluck('user_id')->toArray();

        $ret = self::create([
            'user_id' => $userId,
            'rec_user_ids' => json_encode($recUers),
            'flag' => self::STATUS_UNREAD
        ]);
        return $recUers;
    }
}
